<template>
  <div class="vex-table-container">
    <!-- 表格工具栏 -->
    <div v-if="showToolbar" class="table-toolbar mb-4 flex items-center justify-between">
      <div class="flex items-center space-x-4">
        <slot name="toolbar-left">
          <button
            v-if="showRefresh"
            @click="handleRefresh"
            class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm font-medium rounded-md text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新
          </button>
        </slot>
      </div>
      <div class="flex items-center space-x-2">
        <slot name="toolbar-right">
          <!-- 搜索框 -->
          <div v-if="showSearch" class="relative">
            <input
              v-model="searchText"
              @input="handleSearch"
              type="text"
              placeholder="搜索..."
              class="pl-8 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
            >
            <MagnifyingGlassIcon class="absolute left-2 top-2.5 w-4 h-4 text-gray-400" />
          </div>
        </slot>
      </div>
    </div>

    <!-- VEX TABLE -->
    <vxe-table
      ref="tableRef"
      :data="tableData"
      :loading="loading"
      :height="height"
      :max-height="maxHeight"
      :stripe="stripe"
      :border="border"
      :round="round"
      :size="size"
      :align="align"
      :header-align="headerAlign"
      :highlight-hover-row="highlightHoverRow"
      :highlight-current-row="highlightCurrentRow"
      :row-config="rowConfig"
      :column-config="columnConfig"
      :sort-config="sortConfig"
      :filter-config="filterConfig"
      :export-config="exportConfig"
      :print-config="printConfig"
      :scroll-y="scrollY"
      :scroll-x="scrollX"
      @sort-change="handleSortChange"
      @filter-change="handleFilterChange"
      @current-change="handleCurrentChange"
      @select-change="handleSelectChange"
      @select-all="handleSelectAll"
      class="vex-table-main"
    >
      <!-- 动态列 -->
      <vxe-column
        v-for="column in columns"
        :key="column.field"
        :field="column.field"
        :title="column.title"
        :width="column.width"
        :min-width="column.minWidth"
        :type="column.type"
        :fixed="column.fixed"
        :align="column.align"
        :header-align="column.headerAlign"
        :sortable="column.sortable"
        :filters="column.filters"
        :filter-multiple="column.filterMultiple"
        :show-overflow="column.showOverflow"
        :show-header-overflow="column.showHeaderOverflow"
      >
        <!-- 自定义单元格内容 -->
        <template #default="{ row, column: col }">
          <slot 
            :name="`cell-${column.field}`" 
            :row="row" 
            :column="col" 
            :value="row[column.field]"
          >
            <!-- 状态标签 -->
            <span
              v-if="column.type === 'status'"
              :class="getStatusClass(row[column.field], column)"
              class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
            >
              {{ getStatusLabel(row[column.field], column) }}
            </span>
            <!-- 日期时间 -->
            <span v-else-if="column.type === 'datetime' && row[column.field]">
              {{ formatDateTime(row[column.field]) }}
            </span>
            <!-- 默认显示 -->
            <span v-else>{{ row[column.field] }}</span>
            
          </slot>
        </template>

        <!-- 自定义表头 -->
        <template #header="{ column: col }">
          <slot 
            :name="`header-${column.field}`" 
            :column="col" 
            :title="column.title"
          >
            {{ column.title }}
          </slot>
        </template>
      </vxe-column>

      <!-- 操作列 -->
      <vxe-column
        v-if="actions && actions.length > 0"
        title="操作"
        :width="actionWidth"
        :fixed="actionFixed"
        align="center"
      >
        <template #default="{ row }">
          <slot name="actions" :row="row">
            <div class="flex items-center justify-center space-x-2">
              <button
                v-for="action in actions"
                :key="action.key"
                @click="handleAction(action, row)"
                :class="getActionClass(action)"
                :title="action.label"
                class="inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-colors duration-200"
              >
                <component
                  v-if="action.icon"
                  :is="getActionIcon(action.icon)"
                  class="w-3 h-3 mr-1"
                />
                {{ action.label }}
              </button>
            </div>
          </slot>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 分页器 -->
    <div v-if="showPagination" class="table-pagination mt-4">
      <vxe-pager
        v-model:current-page="paginationData.current"
        v-model:page-size="paginationData.pageSize"
        :total="paginationData.total"
        :page-sizes="pageSizes"
        :layouts="paginationLayouts"
        @page-change="handlePageChange"
        class="vex-pager"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import {
  ArrowPathIcon,
  MagnifyingGlassIcon,
  PencilIcon,
  TrashIcon,
  EyeIcon,
  ShieldCheckIcon,
  KeyIcon
} from '@heroicons/vue/24/outline'
import { useThemeStore } from '@/store/theme'

// Props
interface Column {
  field: string
  title: string
  width?: number
  minWidth?: number
  type?: string
  fixed?: string
  align?: string
  headerAlign?: string
  sortable?: boolean
  filters?: any[]
  filterMultiple?: boolean
  showOverflow?: boolean
  showHeaderOverflow?: boolean
  options?: Array<{ value: any; label: string; color?: string }>
}

interface Action {
  key: string
  label: string
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
  icon?: string
  confirm?: boolean
}

interface PaginationData {
  current: number
  pageSize: number
  total: number
}

const props = withDefaults(defineProps<{
  data: any[]
  columns: Column[]
  loading?: boolean
  height?: number | string
  maxHeight?: number | string
  stripe?: boolean
  border?: boolean
  round?: boolean
  size?: 'mini' | 'small' | 'medium'
  align?: string
  headerAlign?: string
  highlightHoverRow?: boolean
  highlightCurrentRow?: boolean
  rowConfig?: any
  columnConfig?: any
  sortConfig?: any
  filterConfig?: any
  exportConfig?: any
  printConfig?: any
  scrollY?: any
  scrollX?: any
  showToolbar?: boolean
  showRefresh?: boolean
  showSearch?: boolean
  showPagination?: boolean
  pagination?: PaginationData
  pageSizes?: number[]
  paginationLayouts?: string[]
  actions?: Action[]
  actionWidth?: number
  actionFixed?: string
}>(), {
  data: () => [],
  columns: () => [],
  loading: false,
  stripe: true,
  border: true,
  round: true,
  size: 'medium',
  align: 'left',
  headerAlign: 'center',
  highlightHoverRow: true,
  highlightCurrentRow: false,
  showToolbar: true,
  showRefresh: true,
  showSearch: true,
  showPagination: true,
  pagination: () => ({ current: 1, pageSize: 20, total: 0 }),
  pageSizes: () => [10, 20, 50, 100],
  paginationLayouts: () => ['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'Total'],
  actions: () => [],
  actionWidth: 150,
  actionFixed: 'right'
})

// Emits
const emit = defineEmits<{
  refresh: []
  search: [text: string]
  sortChange: [params: any]
  filterChange: [params: any]
  currentChange: [params: any]
  selectChange: [params: any]
  selectAll: [params: any]
  pageChange: [params: any]
  action: [action: Action, row: any]
}>()

// Refs
const tableRef = ref()
const searchText = ref('')
const themeStore = useThemeStore()

// Computed
const tableData = computed(() => props.data)
const paginationData = computed(() => props.pagination)

// Methods
const handleRefresh = () => {
  emit('refresh')
}

const handleSearch = () => {
  emit('search', searchText.value)
}

const handleSortChange = (params: any) => {
  emit('sortChange', params)
}

const handleFilterChange = (params: any) => {
  emit('filterChange', params)
}

const handleCurrentChange = (params: any) => {
  emit('currentChange', params)
}

const handleSelectChange = (params: any) => {
  emit('selectChange', params)
}

const handleSelectAll = (params: any) => {
  emit('selectAll', params)
}

const handlePageChange = (params: any) => {
  emit('pageChange', params)
}

const handleAction = (action: Action, row: any) => {
  if (action.confirm) {
    if (confirm(`确定要${action.label}吗？`)) {
      emit('action', action, row)
    }
  } else {
    emit('action', action, row)
  }
}

const formatDateTime = (dateStr: string | Date) => {
  try {
    const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr
    return format(date, 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
  } catch {
    return dateStr
  }
}

const getStatusClass = (value: any, column: Column) => {
  const option = column.options?.find(opt => opt.value === value)
  const colorMap = {
    green: 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300',
    red: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300',
    yellow: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-300',
    blue: 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300',
    gray: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }
  return colorMap[option?.color as keyof typeof colorMap] || colorMap.gray
}

const getStatusLabel = (value: any, column: Column) => {
  const option = column.options?.find(opt => opt.value === value)
  return option?.label || value
}

const getActionClass = (action: Action) => {
  const typeMap = {
    primary: 'text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:text-blue-300 dark:hover:bg-blue-900/20',
    success: 'text-green-600 hover:text-green-700 hover:bg-green-50 dark:text-green-400 dark:hover:text-green-300 dark:hover:bg-green-900/20',
    warning: 'text-yellow-600 hover:text-yellow-700 hover:bg-yellow-50 dark:text-yellow-400 dark:hover:text-yellow-300 dark:hover:bg-yellow-900/20',
    danger: 'text-red-600 hover:text-red-700 hover:bg-red-50 dark:text-red-400 dark:hover:text-red-300 dark:hover:bg-red-900/20',
    info: 'text-gray-600 hover:text-gray-700 hover:bg-gray-50 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:bg-gray-900/20'
  }
  return typeMap[action.type || 'primary']
}

const getActionIcon = (iconName: string) => {
  const iconMap: Record<string, any> = {
    PencilIcon,
    TrashIcon,
    EyeIcon,
    ShieldCheckIcon,
    KeyIcon
  }
  return iconMap[iconName] || PencilIcon
}

// Watch theme changes and update VXE Table theme
watch(() => themeStore.isDark, (isDark) => {
  // 通过CSS变量动态设置主题
  const root = document.documentElement
  if (isDark) {
    root.style.setProperty('--vxe-table-background-color', '#1F2937')
    root.style.setProperty('--vxe-table-header-background-color', '#374151')
    root.style.setProperty('--vxe-table-header-text-color', '#F3F4F6')
    root.style.setProperty('--vxe-table-body-background-color', '#1F2937')
    root.style.setProperty('--vxe-table-body-text-color', '#F3F4F6')
    root.style.setProperty('--vxe-table-border-color', '#4B5563')
    root.style.setProperty('--vxe-table-hover-background-color', '#374151')
    root.style.setProperty('--vxe-table-stripe-background-color', '#111827')
  } else {
    root.style.setProperty('--vxe-table-background-color', '#FFFFFF')
    root.style.setProperty('--vxe-table-header-background-color', '#F9FAFB')
    root.style.setProperty('--vxe-table-header-text-color', '#374151')
    root.style.setProperty('--vxe-table-body-background-color', '#FFFFFF')
    root.style.setProperty('--vxe-table-body-text-color', '#111827')
    root.style.setProperty('--vxe-table-border-color', '#E5E7EB')
    root.style.setProperty('--vxe-table-hover-background-color', '#F9FAFB')
    root.style.setProperty('--vxe-table-stripe-background-color', '#F9FAFB')
  }
}, { immediate: true })

// Expose methods
defineExpose({
  getTableData: () => tableRef.value?.getTableData(),
  clearSelection: () => tableRef.value?.clearSelection(),
  setAllSelection: (checked: boolean) => tableRef.value?.setAllSelection(checked),
  exportData: (options?: any) => tableRef.value?.exportData(options),
  printData: (options?: any) => tableRef.value?.printData(options)
})
</script>

<style scoped>
.vex-table-container {
  @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;
}

.table-toolbar {
  @apply px-4 py-3 border-b border-gray-200 dark:border-gray-700;
}

.vex-table-main {
  @apply rounded-lg overflow-hidden;
}

.table-pagination {
  @apply px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50;
}

/* VEX TABLE 样式覆盖 */
:deep(.vxe-table) {
  @apply bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100;
}

:deep(.vxe-table .vxe-header--column) {
  @apply bg-gray-50 dark:bg-gray-700 text-gray-700 dark:text-gray-300 font-medium;
}

:deep(.vxe-table .vxe-body--row:hover) {
  @apply bg-gray-50 dark:bg-gray-700/50;
}

:deep(.vxe-table .vxe-body--row.row--stripe) {
  @apply bg-gray-50/50 dark:bg-gray-800/50;
}

:deep(.vxe-pager) {
  @apply bg-transparent;
}

/* 使用CSS变量实现动态主题 */
:deep(.vxe-table) {
  background-color: var(--vxe-table-background-color, #FFFFFF) !important;
  color: var(--vxe-table-body-text-color, #111827) !important;
}

:deep(.vxe-table .vxe-header--column) {
  background-color: var(--vxe-table-header-background-color, #F9FAFB) !important;
  color: var(--vxe-table-header-text-color, #374151) !important;
}

:deep(.vxe-table .vxe-body--row) {
  background-color: var(--vxe-table-body-background-color, #FFFFFF) !important;
  color: var(--vxe-table-body-text-color, #111827) !important;
}

:deep(.vxe-table .vxe-body--row:hover) {
  background-color: var(--vxe-table-hover-background-color, #F9FAFB) !important;
}

:deep(.vxe-table .vxe-body--row.row--stripe) {
  background-color: var(--vxe-table-stripe-background-color, #F9FAFB) !important;
}

:deep(.vxe-table .vxe-body--column) {
  color: var(--vxe-table-body-text-color, #111827) !important;
}

:deep(.vxe-table .vxe-table--border) {
  border-color: var(--vxe-table-border-color, #E5E7EB) !important;
}

:deep(.vxe-table .vxe-table--border .vxe-body--column) {
  border-color: var(--vxe-table-border-color, #E5E7EB) !important;
}

:deep(.vxe-pager) {
  background-color: transparent !important;
  color: var(--vxe-table-body-text-color, #111827) !important;
}

:deep(.vxe-pager .vxe-pager--btn) {
  background-color: var(--vxe-table-header-background-color, #F9FAFB) !important;
  color: var(--vxe-table-header-text-color, #374151) !important;
  border-color: var(--vxe-table-border-color, #E5E7EB) !important;
}

:deep(.vxe-pager .vxe-pager--btn:hover) {
  background-color: var(--vxe-table-hover-background-color, #F9FAFB) !important;
}
</style>
